package com.sky.youxue.service;

import com.sky.youxue.entity.UserInfo;
import com.sky.youxue.common.enums.ExceptionEnum;
import com.sky.youxue.common.exception.youxueException;
import com.sky.youxue.user.pojo.User;
import com.sky.youxue.client.UserClient;
import com.sky.youxue.config.JwtProperties;
import com.sky.youxue.utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;


/**
 * @program: youxue-auth-center
 * @description: 授权业务
 * @author: Mr.Gouyu
 * @create: 2019-01-08 10:18
 **/
@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    private JwtProperties jwtProp ;

    @Autowired
    private UserClient userClient;

    private static Logger logger = LoggerFactory.getLogger(AuthService.class);

    public String authentication(String username , String password){

        //查询用户

//        System.out.println(username+" "+password);
        ResponseEntity<User> responseEntityUser  = this.userClient.queryUser(username , password);

        User user = responseEntityUser.getBody();

        if(null == user) {
            throw new youxueException(ExceptionEnum.INVALID_USERNAME_OR_PASSWORD);
        }

        try{
            //生成token

            String token = JwtUtils.generateToken(
                    new UserInfo(user.getId(),username),
                    jwtProp.getPrivateKey(),jwtProp.getExpire()
            );
            return token;
        }catch (Exception e) {
            throw new youxueException(ExceptionEnum.GENERATE_TOKEN_ERROR);
        }
    }



}
